package com.meichis.yndms.http;

import android.content.Intent;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meichis.mcsappframework.BaseApplication;
import com.meichis.mcsappframework.encrypt.AESProvider;
import com.meichis.mcsappframework.utils.GzipTool;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.yndms.BuildConfig;
import com.meichis.yndms.MCApplication;
import com.meichis.yndms.model.WSIResultPack;
import com.meichis.yndms.repository.manager.TokenManager;
import com.meichis.yndms.ui.activity.LoginActivity;

import java.lang.reflect.Type;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CallSubscriber<T> implements Observer<WSIResultPack> {

    private Disposable disposable;

    private IWebServiceCallback callback;
    private Type type;

    public CallSubscriber(Type type, IWebServiceCallback<Type> callback) {
        this.type = type;
        this.callback = callback;
    }

    @Override
    public void onSubscribe(Disposable disposable) {
        this.disposable = disposable;
        if (!Tools.isConnected(MCApplication.getContext())) {
            callback.onFailure(-1, -1, "当前网络不可用，请检查网络情况");
            onComplete();
        }

    }

    @Override
    public void onNext(WSIResultPack wsiResultPack) {
        if (BuildConfig.DEBUG) {
            Log.v("HttpRequestImpl", "Response:" + new Gson().toJson(wsiResultPack));
        }
        try {
            if (wsiResultPack.getReturn() == -100) {
                MessageTools.showLongToast("长时间未操作，请重新登录！");
                Intent intent = new Intent(BaseApplication.getContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseApplication.getContext().startActivity(intent);
                return;
            }
            if (wsiResultPack.getReturn() < 0) {
                callback.onFailure(wsiResultPack.getSequence(), wsiResultPack.getReturn(), wsiResultPack.getReturnInfo());
                return;
            }
            if (wsiResultPack.getCompressFlag().toLowerCase().equals("y") || ((String) wsiResultPack.getResult()).startsWith("H4sI")) {
                wsiResultPack.setResult(GzipTool.decryptGZIP((String) wsiResultPack.getResult()));
            }
            if (new TypeToken<String>() {
            }.getType() == type) {
                callback.onSucceed(wsiResultPack.getSequence(), wsiResultPack.getResult(), wsiResultPack.getReturnInfo(), wsiResultPack.getReturn());
            } else {
                callback.onSucceed(wsiResultPack.getSequence(), new Gson().fromJson(wsiResultPack.getResult(), type), wsiResultPack.getReturnInfo(), wsiResultPack.getReturn());
            }
            //callback.onSucceed(sequence, wsiResultPack.getResult(), wsiResultPack.getReturnInfo(), wsiResultPack.getReturn());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Exception 请求失败", e.getLocalizedMessage());
            callback.onFailure(wsiResultPack.getSequence(), 0, e.getMessage());
        }
    }

    @Override
    public void onError(Throwable e) {
        if (BuildConfig.DEBUG) {
            Log.v("HttpRequestImpl", "Response:" + e.getMessage());
        }
        if (e.getMessage() != null && e.getMessage().indexOf("invalid_token") >= 0) {
            MessageTools.showLongToast("登录失效，请重新登录！");
            SharePreferenceUtil.getInstance().remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
            TokenManager.setToken();
            Intent intent = new Intent(BaseApplication.getContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BaseApplication.getContext().startActivity(intent);
        } else {
            String errInfo = e.getMessage().indexOf("→") > 0 ? e.getMessage().split("→")[1] : e.getMessage();
            int sequence = -1;
            try {
                if (errInfo.contains("returnInfo")) {
                    WSIResultPack resultPack = new Gson().fromJson(errInfo, WSIResultPack.class);
                    errInfo = resultPack.getReturnInfo();
                    sequence = resultPack.getSequence();
                }
            } catch (Exception exception) {
                errInfo = e.getMessage();
            }
            callback.onFailure(sequence, -1, errInfo);
        }
        onComplete();
    }

    @Override
    public void onComplete() {
        if (!disposable.isDisposed()) {
            disposable.dispose();
        }
    }


}
